﻿import 'dart:async';
import 'package:azring/core/repository/default_api.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/common/langs/text_key.dart';
import 'package:azring/common/res/gaps.dart';
import 'package:azring/common/utils/change_notifier_manage.dart';
import 'package:azring/common/utils/keyboard_util.dart';
import 'package:azring/pages/login/login/login_logic.dart';
import 'package:azring/pages/login/login/login_state.dart';
import 'package:azring/widget/my_scroll_view.dart';
import 'package:azring/pages/login/login_router.dart';

/// design/1注册登录/index.html#artboard11
class RegisterView extends StatefulWidget {
  const RegisterView({super.key});

  @override
  _RegisterViewState createState() => _RegisterViewState();
}

class _RegisterViewState extends State<RegisterView>
    with ChangeNotifierMixin<RegisterView> {
  //定义一个Logic
  final TextEditingController _nameLogic = TextEditingController();
  final TextEditingController _vCodeLogic = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  bool _clickable = false;
  bool _agreeTerms = false;
  String? _sendUUID;
  bool _isFirstFieldFocused = false;
  bool _isSecondFieldFocused = false;
  final LoginLogic logic = Get.put(LoginLogic());
  final LoginState state = Get.find<LoginLogic>().state;

  // 验证码倒计时相关状态 - 使用GetX响应式变量
  Timer? _countdownTimer;
  final RxInt _countdownSeconds = 0.obs;
  final RxBool _isCountdownActive = false.obs;
  final RxBool _canSendCode = false.obs;

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _nameLogic: callbacks,
      _vCodeLogic: callbacks,
      _nodeText1: null,
      _nodeText2: null,
    };
  }

  @override
  void initState() {
    super.initState();
    // 添加焦点监听器
    _nodeText1.addListener(_onFocusChange);
    _nodeText2.addListener(_onFocusChange);
  }

  void _onFocusChange() {
    if (mounted) {
      setState(() {
        _isFirstFieldFocused = _nodeText1.hasFocus;
        _isSecondFieldFocused = _nodeText2.hasFocus;
        print(
            '注册页焦点变化: node1=${_nodeText1.hasFocus}, node2=${_nodeText2.hasFocus}');
      });
    }
  }

  @override
  void dispose() {
    _nodeText1.removeListener(_onFocusChange);
    _nodeText2.removeListener(_onFocusChange);
    _countdownTimer?.cancel();
    super.dispose();
  }

  void _verify() {
    final String name = _nameLogic.text;
    final String vCode = _vCodeLogic.text;
    bool clickable = true;
    if (name.isEmpty || name.length < 4) {
      clickable = false;
    }
    if (vCode.isEmpty || vCode.length < 4) {
      clickable = false;
    }
    if (!_agreeTerms) {
      clickable = false;
    }
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }

    // 检查是否可以发送验证码
    bool canSend = _isValidPhoneOrEmail(name) && !_isCountdownActive.value;
    if (canSend != _canSendCode.value) {
      _canSendCode.value = canSend;
    }
  }

  // 验证手机号或邮箱格式
  bool _isValidPhoneOrEmail(String input) {
    if (input.isEmpty) return false;

    // 手机号验证（11位数字）
    if (RegExp(r'^1[3-9]\d{9}$').hasMatch(input)) {
      return true;
    }

    // 邮箱验证
    if (RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
        .hasMatch(input)) {
      return true;
    }

    return false;
  }

  void _register() {
    // 跳转到设置密码页面，传递注册信息
    Get.toNamed(LoginRouter.setPasswordPage, arguments: {
      'username': _nameLogic.text,
      'code': _vCodeLogic.text,
      'uuid': _sendUUID,
    });
  }

  // 开始倒计时
  void _startCountdown() {
    _countdownSeconds.value = 50;
    _isCountdownActive.value = true;
    _canSendCode.value = false;

    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdownSeconds.value > 0) {
        _countdownSeconds.value--;
      } else {
        _stopCountdown();
      }
    });
  }

  // 停止倒计时
  void _stopCountdown() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    _isCountdownActive.value = false;
    _countdownSeconds.value = 0;
    _verify(); // 重新检查是否可以发送验证码
  }

  // 发送验证码
  Future<void> _sendVerificationCode() async {
    if (!_canSendCode.value) return;

    try {
      dynamic response = await DefaultApi()
          .sendSmsChinaGet(phone: _nameLogic.text.toString());
      print(response);
      if (response != null) {
        _sendUUID = response['uuid'];
        _startCountdown();
        Toast.show('验证码发送成功');
      }
    } catch (e) {
      print(e);
      Toast.show('验证码发送失败，请重试');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MyScrollView(
      keyboardConfig: KeyboardUtil.getKeyboardActionsConfig(
          context, <FocusNode>[_nodeText1, _nodeText2]),
      padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0),
      children: _buildBody(),
    );
  }

  List<Widget> _buildBody() {
    return <Widget>[
      Gaps.vGap21,
      // 输入框区域
      _buildInputSection(),
      Gaps.vGap21,
      // 按钮区域
      _buildButtonSection(),
      Gaps.vGap35,
      // 同意条款
      _buildTermsSection(),
      SizedBox(height: 140.h),
      // 注册按钮
      _buildRegisterButton(),
    ];
  }

  // 构建输入框区域
  Widget _buildInputSection() {
    return Column(
      children: [
        Container(
          height: 56.h,
          decoration: BoxDecoration(
            color: const Color(0xFF282528),
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(
              color: _isFirstFieldFocused
                  ? const Color(0xffF45757)
                  : Colors.transparent,
              width: 0.5.w,
            ),
          ),
          child: TextField(
            focusNode: _nodeText1,
            controller: _nameLogic,
            style: const TextStyle(color: Colors.white, fontSize: 14),
            keyboardType: TextInputType.emailAddress,
            textAlignVertical: TextAlignVertical.center,
            onTap: () {
              setState(() {
                // 确保焦点变化时更新UI
              });
            },
            decoration: InputDecoration(
              hintText: "请输入手机或者邮箱号码",
              hintStyle: TextStyle(color: Colors.white, fontSize: 14.sp),
              border: InputBorder.none,
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 25, vertical: 18),
            ),
          ),
        ),
        Gaps.vGap18,
        Container(
          height: 56.h,
          decoration: BoxDecoration(
            color: const Color(0xFF282528),
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(
              color: _isSecondFieldFocused
                  ? const Color(0xffF46425)
                  : Colors.transparent,
              width: 0.5.w,
            ),
          ),
          child: TextField(
            focusNode: _nodeText2,
            controller: _vCodeLogic,
            style: const TextStyle(color: Colors.white, fontSize: 14),
            keyboardType: TextInputType.number,
            textAlignVertical: TextAlignVertical.center,
            onTap: () async {
              // 移除原来的逻辑，改为点击验证码按钮时调用
            },
            decoration: InputDecoration(
              hintText: "请输入验证码",
              hintStyle: const TextStyle(color: Colors.white, fontSize: 14),
              border: InputBorder.none,
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 25, vertical: 18),
              suffixIcon: Obx(() => GestureDetector(
                    onTap: _canSendCode.value ? _sendVerificationCode : null,
                    child: Container(
                      margin: const EdgeInsets.all(8),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 8),
                      child: Text(
                        _isCountdownActive.value
                            ? "${_countdownSeconds.value}秒后重发"
                            : "获取验证码",
                        style: TextStyle(
                          color: _canSendCode.value
                              ? const Color(0xffF46425)
                              : const Color(0xffF46425).withOpacity(0.65),
                          fontSize: 12.sp,
                        ),
                      ),
                    ),
                  )),
            ),
          ),
        ),
      ],
    );
  }

  // 构建按钮区域
  Widget _buildButtonSection() {
    return Row(
      children: [
        const Spacer(),
        GestureDetector(
          onTap: () {
            // 处理获取不到验证码
          },
          child: Container(
            width: 120.w,
            height: 32.h,
            decoration: BoxDecoration(
              border: Border.all(color: const Color(0xffF46425)),
              borderRadius: BorderRadius.circular(18.r),
            ),
            child: Center(
              child: Text(
                "获取不到验证码",
                style: TextStyle(
                  color: Color(0xffF46425),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w300,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建同意条款区域
  Widget _buildTermsSection() {
    return Row(
      children: [
        Gaps.hGap16,
        GestureDetector(
          onTap: () {
            setState(() {
              _agreeTerms = !_agreeTerms;
              _verify();
            });
          },
          child: Container(
            width: 14.w,
            height: 14.h,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: _agreeTerms ? const Color(0xffF46425) : Colors.transparent,
              border: Border.all(
                color: _agreeTerms
                    ? const Color(0xffF46425)
                    : const Color(0xFF666666),
                width: 1,
              ),
            ),
            child: _agreeTerms
                ? const Icon(
                    Icons.check,
                    color: Colors.white,
                    size: 14,
                  )
                : null,
          ),
        ),
        Gaps.hGap8,
        Expanded(
          child: RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: TextKey.agreeTerms.tr, // "我已阅读并同意"
                  style: TextStyle(color: Colors.white),
                ),
                TextSpan(
                  text: TextKey.terms.tr, // "使用条款"
                  style: TextStyle(color: Color(0xffF46425)),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      // 处理使用条款点击
                    },
                ),
                TextSpan(
                  text: TextKey.and.tr, // "和"
                  style: TextStyle(color: Colors.white),
                ),
                TextSpan(
                  text: TextKey.privacy.tr, // "隐私政策"
                  style: const TextStyle(color: Color(0xffF46425)),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      // 处理隐私政策点击
                    },
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 构建注册按钮
  Widget _buildRegisterButton() {
    return Container(
      width: double.infinity,
      height: 56.h,
      decoration: BoxDecoration(
        color: _clickable
            ? const Color(0xffF46425)
            : const Color(0xffF46425).withOpacity(0.5),
        borderRadius: BorderRadius.circular(999.r),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: _clickable ? _register : null,
          borderRadius: BorderRadius.circular(999.r),
          child: Center(
            child: Text(
              '下一步',
              style: TextStyle(
                color:
                    _clickable ? Colors.white : Colors.white.withOpacity(0.5),
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
